#ifndef QXGAME_GAMEBUTTON_H
#define QXGAME_GAMEBUTTON_H

#include <atomic>
#include <string>
#include <functional>
#include "GameFont.h"
#include "SDL.h"
#include "SDL_ttf.h"
#include "GameVector.h"
#include "GameTest.h"

class GameButton {
public:
    bool IsMouseOver(const SDL_Event &event) const
    {
        int mouseX = event.motion.x, mouseY = event.motion.y;
        return mouseX >= position.x - width / 2 && mouseX < position.x + width / 2 &&
               mouseY >= position.y - height / 2 && mouseY < position.y + height / 2;
    }

    void OnInput(const SDL_Event &e)
    {
        if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == SDL_BUTTON_LEFT && IsMouseOver(e)) {
            isPressed = true;
        } else if (e.type == SDL_MOUSEBUTTONUP && e.button.button == SDL_BUTTON_LEFT && isPressed) {
            isPressed = false;
            if (IsMouseOver(e)) {
                onClick();
            }
        }
    }

    void Render(SDL_Renderer *renderer) const
    {
        if (test_mode_flag) {
            RendererRect({(double)position.x, (double)position.y}, {(double)width, (double)height, 0, ShapeType::RECT}, {0, 0, 0});
        }

        SDL_Rect rect = {position.x - texWidth / 2, position.y - texHeight / 2, texWidth, texHeight};
        if (isDisable) {
            SDL_RenderCopy(renderer, texDisable, nullptr, &rect);
        }
        if (isPressed) {
            SDL_RenderCopy(renderer, texHover, nullptr, &rect);
        }
        SDL_RenderCopy(renderer, texNormal, nullptr, &rect);
    }

    void Render(SDL_Renderer *renderer, TTF_Font *font, SDL_Color color, const std::string &str) const
    {
        Render(renderer);
        static GameFont gameFont;
        gameFont.OnRender(renderer, font, position, color, str);
    }

public:
    SDL_Point position;
    SDL_Texture *texNormal = nullptr;
    SDL_Texture *texHover = nullptr;
    SDL_Texture *texDisable = nullptr;
    int texWidth = 0;
    int texHeight = 0;
    int width = 0;
    int height = 0;
    std::atomic<bool> isPressed = false;             // 按钮是否被按下
    std::atomic<bool> isDisable = false;             // 按钮是否使能
    std::function<void()> onClick;
};


#endif //QXGAME_GAMEBUTTON_H
